package com.api_gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class JwtConfigValidator implements ApplicationListener<ApplicationReadyEvent> {

    @Value("${jwt.secret:}")
    private String secretKey;

    @Override
    public void onApplicationEvent( ApplicationReadyEvent event) {
        if (secretKey == null || secretKey.trim().isEmpty()) {
            log.error(" JWT secret key is not configured!");
            log.error(" Please add the following to your application.yml:");
            log.error("jwt:");
            log.error("  secret: your-very-long-and-secure-random-string-here");
            log.error(" You can generate a secure key using: openssl rand -base64 32");

            // 在开发环境中可以提供临时方案
            if (isDevelopment()) {
                log.warn(" Using INSECURE default key for development only!");
            } else {
                throw new IllegalStateException("JWT secret key must be configured in production");
            }
        } else {
            if (secretKey.length() < 64) {
                log.warn("JWT secret key is too short ({} characters). For HS512 algorithm, recommended length is at least 64 characters.",
                        secretKey.length());
            }
            log.info(" JWT secret key is configured (length: {} characters)", secretKey.length());
        }
    }

    private boolean isDevelopment() {
        String env = System.getProperty("spring.profiles.active", "");
        return env.contains("dev") || env.contains("local");
    }
}